package com.tutucms.common.util;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.*;

/**
 * Title:读取配置文件信息
 * Description:cn.com.wxd.util
 *
 * @author WangXuDong
 * @version 1.0
 */
public class ConfigFileUtil {

    private static final Logger log = LoggerFactory.getLogger(ConfigFileUtil.class);

    /**
     * 读取配置文件的信息
     *
     * @param fileName 文件名(默认从classpath跟目录向后扫描所有pachage，直到到jar包中，
     *                 如果文件名中包含了指定路径，那么只从给该路径中读取)
     * @param field    字段名称
     * @return 如果未定义或者不存在则返回空字符串
     */
    public static String readPropertiesConfig(String fileName, String field) {
        String retStr;
        Configuration config;
        if (!fileName.contains(".properties")) {
            fileName = fileName + ".properties";
        }
        try {
            if (fileName.contains("/") || fileName.contains("\\")) {
                if (fileName.startsWith("/") || fileName.contains(":")) {
                    config = new PropertiesConfiguration(new File(fileName));
                } else {
                    config = new PropertiesConfiguration(ConfigFileUtil.class.getClassLoader().getResource(fileName));
                }
            } else {
                config = new PropertiesConfiguration(fileName);
            }
            retStr = config.getString(field);
        } catch (Exception e) {
            log.error("Configuration File Read error:" + fileName, e);
            return "";
        }
        return retStr;
    }

    /**
     * 读取配置文件的信息
     *
     * @param fileName 文件名(默认从classpath跟目录向后扫描所有pachage，直到到jar包中，
     *                 如果文件名中包含了指定路径，那么只从给该路径中读取)
     * @return 如果未定义或者不存在则返回空字符串
     */
    public static Map<String, String> readPropertiesConfig(String fileName) {
        Configuration config;
        Map<String, String> map = new HashMap<>();
        if (!fileName.contains(".properties")) {
            fileName = fileName + ".properties";
        }
        try {
            if (fileName.contains("/") || fileName.contains("\\")) {
                if (fileName.startsWith("/") || fileName.contains(":")) {
                    config = new PropertiesConfiguration(new File(fileName));
                } else {
                    config = new PropertiesConfiguration(ConfigFileUtil.class.getClassLoader().getResource(fileName));
                }
            } else {
                config = new PropertiesConfiguration(fileName);
            }
        } catch (Exception e) {
            log.error("Configuration File Read error:" + fileName, e);
            return map;
        }
        Iterator<String> iterator = config.getKeys();
        while (iterator.hasNext()) {
            String key = iterator.next();
            map.put(key, config.getString(key));
        }
        return map;
    }

    /**
     * 输入一个正确的路径
     * 按行读取一个字符文件
     *
     * @return
     */
    public static List<String> readCharFilebyLine(String path) {
        List<String> list = new ArrayList<>();
        File file = new File(path);
        if (file.isDirectory()) {
            log.error("Please specify character file, rather than a directory" + path);
            return null;
        }
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String s;
            while ((s = br.readLine()) != null) {//使用readLine方法，一次读一行
                list.add(s);
            }
        } catch (Exception e) {
            log.error("Char FileRead error:" + path, e);
            return null;
        }

        return list;
    }

    /**
     * 输入一个正确的路径
     * 按行读取一个字符文件
     *
     * @param maxLine maxLine = -1 表示读取所有行
     * @return
     */
    public static List<String> readCharFileByLine(String path, int maxLine) {
        File file = new File(path);
        if (file.isDirectory()) {
            log.error("Please specify character file, rather than a directory" + path);
            return null;
        }
        try {
            return readCharFileByLine(new FileInputStream(file), maxLine);
        } catch (FileNotFoundException e) {
            log.error("file is not found,", file.getPath(), e);
            return null;
        }
    }

    /**
     * 输入一个正确的路径
     * 按行读取一个字符文件
     *
     * @param maxLine maxLine = -1 表示读取所有行
     * @return
     */
    public static List<String> readCharFileByLine(InputStream inputStream, int maxLine) {
        List<String> list = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
            String s;
            int lineNum = 0;
            while ((s = br.readLine()) != null) {//使用readLine方法，一次读一行
                if (lineNum >= maxLine && maxLine > -1) {
                    break;
                }
                list.add(s);
                lineNum++;
            }
            return list;
        } catch (Exception e) {
            log.error("Char FileRead error:", e);
        }
        return null;
    }

    /**
     * 读取一个文件，按行读取
     *
     * @param maxLine 最大行数，-1表示全部行
     */
    public static List<String> readCharFileByLineFromResource(String fileName, int maxLine) {
        // 读取验证码模板
        InputStream inputStream = ConfigFileUtil.class.getClassLoader().getResourceAsStream(fileName);
        return ConfigFileUtil.readCharFileByLine(inputStream, maxLine);
    }

    /**
     * 读取一个文件
     */
    public static String readCharFileFromResource(String fileName) {
        // 读取验证码模板
        List<String> lines = readCharFileByLineFromResource(fileName, -1);
        if (CollectionUtils.isEmpty(lines)) {
            return null;
        }
        StringBuilder builder = new StringBuilder("");
        lines.forEach(builder::append);
        return builder.toString();
    }
}
